package com.btex.app;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.btex.app.adapter.OTCStateImagAdapter;
import com.btex.app.adapter.OTCStateListAdapter;
import com.btex.app.entity.OTCStateListInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.google.gson.Gson;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.taobao.windvane.config.GlobalConfig.context;

/**
 * 申述
 */

public class OTCStateActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.activity_otc_tv_state_name)
    TextView mActivityOtcTvStateName;
    @BindView(R.id.activity_otc_recy_state)
    RecyclerView mActivityOtcRecyState;
    @BindView(R.id.activity_otc_imag_state)
    ImageView mActivityOtcImagState;
    @BindView(R.id.activity_otc_imag_state_wei_money)
    ImageView mActivityOtcImagStateWeiMoney;
    @BindView(R.id.activity_otc_imag_state_wei_bi)
    ImageView mActivityOtcImagStateWeiBi;
    @BindView(R.id.activity_otc_lin_state_wei_bi)
    LinearLayout mActivityOtcLinStateWeiBi;
    @BindView(R.id.activity_otc_lin_state_wei_money)
    LinearLayout mActivityOtcLinStateWeiMoney;
    @BindView(R.id.activity_otc_imag_state_other)
    ImageView mActivityOtcImagStateOther;
    @BindView(R.id.activity_otc_lin_state_other)
    LinearLayout mActivityOtcLinStateOther;
    @BindView(R.id.activity_otc_ed_state)
    EditText mActivityOtcEdState;
    @BindView(R.id.otc_activity_tv_state_diss)
    TextView mOtcActivityTvStateDiss;
    @BindView(R.id.otc_activity_tv_state_yi)
    TextView mOtcActivityTvStateYi;
    @BindView(R.id.otc_activity_recy_state_record)
    RecyclerView mOtcActivityRecyStateRecord;
    private List<Uri> mUris;
    List<String> photoPath = new ArrayList<>();
    private LinearLayoutManager mLayoutManager;
    private SharedPreferencesUtil mSharedPreferences;
    private MicroAVLIDialog mMicroAVLIDialog;
    private String mTrade_id;
    private String typ = "";
    private OTCStateListAdapter mOtcStateListAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otcstate);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mTvTitle.setText("申述");
        mTrade_id = getIntent().getStringExtra("data");
//        Log.i("qwkdjnqwidjiqowjd", mTrade_id);
        initAdapter();

        mActivityOtcTvStateName.setText("对订单" + mTrade_id + "的申述");

        mMicroAVLIDialog = new MicroAVLIDialog(this);
        mSharedPreferences = SharedPreferencesUtil.getSharedPreferences(context);
        initOtcData();
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    }

    private void initAdapter() {
        mLinearLayoutManager = new LinearLayoutManager(OTCStateActivity.this);
        mOtcActivityRecyStateRecord.setLayoutManager(mLinearLayoutManager);
        mOtcStateListAdapter = new OTCStateListAdapter(OTCStateActivity.this);
        mOtcActivityRecyStateRecord.setAdapter(mOtcStateListAdapter);
    }

    private void initOtcData() {

        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(MyApplication.getContextObject(), sp);
        x.Ext.init(getApplication());
        RequestParams params = new RequestParams(Config.GET_OTC_APPEAL_LISTS);
        params.addQueryStringParameter("trade_id", mTrade_id);

        params.addHeader("token", sp.getString(Config.TOKEN, null));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mMicroAVLIDialog.dismiss();
                Log.i("wdqowdjnhfkwuhkqp", result);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);

                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {

                        Gson gson = new Gson();
                        OTCStateListInfo otcStateListInfo = gson.fromJson(result, OTCStateListInfo.class);
                        List<OTCStateListInfo.DataBean> data = otcStateListInfo.getData();

                        if (data.size() > 0) {

                            Log.i("kwjndqwudhihuw", "111");

                            mOtcStateListAdapter.setNewData(data);
                        } else {

                            mOtcStateListAdapter.setEmptyView(R.layout.otc_empty, mOtcActivityRecyStateRecord);

                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                mMicroAVLIDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mMicroAVLIDialog.dismiss();
            }

            @Override
            public void onFinished() {
                mMicroAVLIDialog.dismiss();
            }
        });


    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.iv_back, R.id.activity_otc_imag_state, R.id.activity_otc_lin_state_wei_bi, R.id.activity_otc_lin_state_wei_money, R.id.activity_otc_lin_state_other, R.id.otc_activity_tv_state_diss, R.id.otc_activity_tv_state_yi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.activity_otc_imag_state:


                if (photoPath.size() >= 3) {
//                    SnackbarShow("图片不能超过3张");
                    Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.red),"图片不能超过3张");
                    return;
                }

                Matisse.from(OTCStateActivity.this)
                        .choose(MimeType.allOf()) // 选择 mime 的类型
                        .countable(true)
                        .theme(R.style.Matisse_Dracula)
                        .maxSelectable(3) // 图片选择的最多数量
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f) // 缩略图的比例
                        .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                        .forResult(100); // 设置作为标记的请求码


                break;
            case R.id.activity_otc_lin_state_wei_bi:
                typ = "0";
                setImagState();
                mActivityOtcImagStateWeiBi.setBackground(getResources().getDrawable(R.mipmap.otc_xuanzhe));

                break;
            case R.id.activity_otc_lin_state_wei_money:
                typ = "1";
                setImagState();
                mActivityOtcImagStateWeiMoney.setBackground(getResources().getDrawable(R.mipmap.otc_xuanzhe));
                break;
            case R.id.activity_otc_lin_state_other:
                typ = "2";
                setImagState();
                mActivityOtcImagStateOther.setBackground(getResources().getDrawable(R.mipmap.otc_xuanzhe));
                break;
            case R.id.otc_activity_tv_state_diss:
                finish();
                break;
            case R.id.otc_activity_tv_state_yi:

                if (TextUtils.isEmpty(mActivityOtcEdState.getText().toString())) {
//                    SnackbarShow("描述内容不能为空");
                    Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.red),"描述内容不能为空");
                    return;
                }
                setOtcData();

                break;
        }
    }

    private void setImagState() {
        mActivityOtcImagStateOther.setBackground(getResources().getDrawable(R.mipmap.otc_nomal_xuan));
        mActivityOtcImagStateWeiBi.setBackground(getResources().getDrawable(R.mipmap.otc_nomal_xuan));
        mActivityOtcImagStateWeiMoney.setBackground(getResources().getDrawable(R.mipmap.otc_nomal_xuan));

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {

            List<Uri> uris = Matisse.obtainResult(data);

            for (int i = 0; i < uris.size(); i++) {
                String realFilePath = getRealFilePath(this, uris.get(i));
                photoPath.add(realFilePath);

            }

            OTCStateImagAdapter otcStateImagAdapter = new OTCStateImagAdapter(photoPath, this);
            mActivityOtcRecyState.setLayoutManager(mLayoutManager);
            mActivityOtcRecyState.setAdapter(otcStateImagAdapter);


        }
    }

    private void setOtcData() {

        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(MyApplication.getContextObject(), sp);
        x.Ext.init(getApplication());
        RequestParams params = new RequestParams(Config.OTC_APPEAL);
        params.setMultipart(true);


        List<KeyValue> list = new ArrayList<>();

        for (int i = 0; i < photoPath.size(); i++) {
            list.add(new KeyValue("img[]", new File(photoPath.get(i))));

        }
        list.add(new KeyValue("trade_id", mTrade_id));
        list.add(new KeyValue("content", mActivityOtcEdState.getText()));
        list.add(new KeyValue("lang", "zh_cn"));

        //myclient=android
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.addHeader("token", sp.getString(Config.TOKEN, null));
        params.addHeader("myclient", "android");
        params.setUseCookie(true);
        params.setRequestBody(body);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.i("12345432", result);

                mMicroAVLIDialog.dismiss();
                try {

                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        initOtcData();
                        Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.bg_green),jsonObject.getString("info"));
                    } else {
                        Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.red),jsonObject.getString("info"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mMicroAVLIDialog.dismiss();
//                SnackbarShow("上传失败");
                Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.red),"上传失败");

            }

            @Override
            public void onCancelled(CancelledException cex) {
                mMicroAVLIDialog.dismiss();
//                SnackbarShow("上传失败");
                Util.showSnachBar(OTCStateActivity.this, getResources().getColor(R.color.red),"上传失败");
            }

            @Override
            public void onFinished() {
                mMicroAVLIDialog.dismiss();
            }
        });

    }


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {

//        Log.i("kqwuhqiwuhdq", "" + event);
//        if (Integer.parseInt(event) == 0) {
//            return;
//        } else {
//
//            photoPath.remove(Integer.parseInt(event));
//            int size = photoPath.size();
//            Log.i("jqwhfqjygwf", "" + size);
//        }

        int size = photoPath.size();
        Log.i("jqwhfqjygwf", "" + size);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


//    private void SnackbarShow(String ms) {
//
//        Snackbar snackbar = ShortSnackbar(mActivityOtcEdState, ms, Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//        snackbar.show();
//    }
//
//    public static Snackbar ShortSnackbar(View view, String message, int messageColor, int backgroundColor) {
//        Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
//        setSnackbarColor(snackbar, messageColor, backgroundColor);
//        return snackbar;
//    }
//
//    /**
//     * 设置Snackbar文字和背景颜色
//     *
//     * @param snackbar
//     * @param messageColor
//     * @param backgroundColor
//     */
//    public static void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) {
//        View view = snackbar.getView();
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            TextView message = (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
//            //View.setTextAlignment需要SDK>=17
//            message.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);
//            message.setGravity(Gravity.CENTER);
//        }
//
//        if (view != null) {
//            view.setBackgroundColor(backgroundColor);
//            ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);
//        }
//    }


}
